using NewLife.Caching;

namespace Aurora.Redis.NewLifeRedis;

public class NewLifeRedisFactory
{
    private readonly string _connection;

    public NewLifeRedisFactory(string connection)
    {
        _connection = connection;
    }
    private volatile FullRedis _redis;
    private readonly object _lock = new object();

    /// <summary>
    /// 获取实例
    /// </summary>
    /// <returns></returns>
    /// <exception cref="Exception"></exception>
    public FullRedis Get()
    {
        if (_redis != null) return _redis;
        lock (_lock)
        {
            if (_redis != null)
            {
                _redis.Dispose();
            }
            
            try
            {
                Console.WriteLine("[Redis创建]进行了NewLife.Redis 的创建");
                _redis = FullRedis.Create(_connection);
            }
            catch (Exception ex)
            {
                throw new Exception("Redis服务未启用，请开启该服务," + ex.Message);
            }
        }

        return _redis;
    }

    public void Dispose()
    {
        if (_redis != null)
        {
            _redis.Dispose();
        }
    }
}